#include <stdio.h>
#include <string.h>
#include "database.h"
#include "stack.h"
int pwd_command(MYSQL* conn, DirStack* stack, const char* user_name, char* result) {
    result[0] = '\0'; // 清空输出

    if (stack->top < 0) {
        strcpy(result, "/");
        return 0;
    }

    for (int i = 1; i <= stack->top; ++i) { // 注意：跳过根目录（id=1），它 name 是 "/"
        int dir_id = stack->dirs[i];

        MYSQL_STMT* stmt = mysql_stmt_init(conn);
        if (!stmt) {
            strcpy(result, "stmt init failed\n");
            return -1;
        }

        const char* sql = "SELECT name FROM nodes WHERE id=? AND user_name=?";
        if (mysql_stmt_prepare(stmt, sql, strlen(sql)) != 0) {
            sprintf(result, "prepare error: %s\n", mysql_stmt_error(stmt));
            mysql_stmt_close(stmt);
            return -1;
        }

        MYSQL_BIND bind[2];
        memset(bind, 0, sizeof(bind));

        bind[0].buffer_type = MYSQL_TYPE_LONG;
        bind[0].buffer = &dir_id;

        bind[1].buffer_type = MYSQL_TYPE_STRING;
        bind[1].buffer = (void*)user_name;
        bind[1].buffer_length = strlen(user_name);

        if (mysql_stmt_bind_param(stmt, bind) != 0) {
            sprintf(result, "bind error: %s\n", mysql_stmt_error(stmt));
            mysql_stmt_close(stmt);
            return -1;
        }

        if (mysql_stmt_execute(stmt) != 0) {
            sprintf(result, "execute error: %s\n", mysql_stmt_error(stmt));
            mysql_stmt_close(stmt);
            return -1;
        }

        char name[256];
        MYSQL_BIND res;
        memset(&res, 0, sizeof(res));

        res.buffer_type = MYSQL_TYPE_STRING;
        res.buffer = name;
        res.buffer_length = sizeof(name);

        if (mysql_stmt_bind_result(stmt, &res) != 0) {
            sprintf(result, "bind result error: %s\n", mysql_stmt_error(stmt));
            mysql_stmt_close(stmt);
            return -1;
        }

        if (mysql_stmt_fetch(stmt) == 0) {
            strcat(result, "/");
            strcat(result, name);
        }

        mysql_stmt_close(stmt);
    }

    // 根目录时为空，补一个 "/"
    if (strlen(result) == 0) {
        strcpy(result, "/");
    }

    return 0;
}

